package com.cheer.ba.view.activity;

import android.os.Handler;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.OilCardInfoModel;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.utils.A2bigA;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.pickerview.Util;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 添加司机
 */
public class AddDriversAty extends BaseCommAty {

    @BindView(R.id.id_driver_name_edit)
    EditText mEditDriverName;
    private String mSaveName;
    @BindView(R.id.id_driver_first_txt)
    TextView mTxtDriverFirst;
    private String mSaveDriverFirst;
    @BindView(R.id.id_driver_platenum_edit)
    EditText mEditDriverPlateNum;
    private String mSavePlateNum;
    @BindView(R.id.id_driver_tel_edit)
    EditText mEditDriverTel;
    private String mSaveTel;
    @BindView(R.id.id_driver_idcard_edit)
    EditText mEditDriverIdCard;
    private String mSaveIdCard;
    @BindView(R.id.id_driver_oil_num_edit)
    EditText mEditDriverOilNum;
    private String mSaveOilNum;

    private static final char kongge = ' ';

    //存储车辆前缀
    private ArrayList<String> mSaveCarLs = new ArrayList<String>();

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_add_driver, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new OilMealPresenter();
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initView() {
        setTitleText("添加司机");
        mEditDriverPlateNum.setTransformationMethod(new A2bigA());
        mEditDriverPlateNum.setText("A");
        mEditDriverPlateNum.setSelection(mEditDriverPlateNum.length());

        String[] s = getResources().getStringArray(R.array.spingarr);
        mSaveCarLs.clear();
        mSaveCarLs.addAll(Arrays.asList(s));
    }

    @Override
    public void initData() {
        mEditDriverOilNum.addTextChangedListener(new TextWatcher() {
            // 改变之前text长度
            int beforeTextLength = 0;
            // 改变之前的文字
            private CharSequence beforeChar;
            // 改变之后text长度
            int onTextLength = 0;
            // 是否改变空格或光标
            boolean isChanged = false;
            // 记录光标的位置
            int location = 0;
            private char[] tempChar;
            private StringBuffer buffer = new StringBuffer();
            // 已有空格数量
            int konggeNumberB = 0;

            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2,
                                      int arg3) {
                onTextLength = s.length();
                buffer.append(s.toString());
                if (onTextLength == beforeTextLength || onTextLength <= 3
                        || isChanged) {
                    isChanged = false;
                    return;
                }
                isChanged = true;
            }

            @Override
            public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                                          int arg3) {
                beforeTextLength = s.length();
                if (buffer.length() > 0) {
                    buffer.delete(0, buffer.length());
                }
                konggeNumberB = 0;
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) == ' ') {
                        konggeNumberB++;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isChanged) {
                    location = mEditDriverOilNum.getSelectionEnd();
                    int index = 0;
                    while (index < buffer.length()) {
                        if (buffer.charAt(index) == kongge) {
                            buffer.deleteCharAt(index);
                        } else {
                            index++;
                        }
                    }
                    index = 0;
                    int konggeNumberC = 0;
                    while (index < buffer.length()) {
                        if ((index - 4) % 5 == 0) {
                            buffer.insert(index, kongge);
                            konggeNumberC++;
                        }
                        index++;
                    }

                    if (konggeNumberC > konggeNumberB) {
                        location += (konggeNumberC - konggeNumberB);
                    }

                    tempChar = new char[buffer.length()];
                    buffer.getChars(0, buffer.length(), tempChar, 0);
                    String str = buffer.toString();
                    if (location > str.length()) {
                        location = str.length();
                    } else if (location < 0) {
                        location = 0;
                    }
                    mEditDriverOilNum.setText(str);
                    Editable etable = mEditDriverOilNum.getText();
                    Selection.setSelection(etable, location);
                    isChanged = false;
                }
            }
        });
    }

    private boolean checkData() {
        mSaveName = mEditDriverName.getText().toString().trim();
        mSaveDriverFirst = mTxtDriverFirst.getText().toString().trim();
        mSavePlateNum = mEditDriverPlateNum.getText().toString().trim().toUpperCase();
        mSaveTel = mEditDriverTel.getText().toString().trim();
        mSaveIdCard = mEditDriverIdCard.getText().toString().trim();
        mSaveOilNum = mEditDriverOilNum.getText().toString().trim().replaceAll(" ", "").trim();
        if (StringUtils.isEmpty(mSaveName)) {
            SVProgressHUD.showInfoWithStatus(aty, "请输入司机姓名");
        } else {
            if (StringUtils.isEmpty(mSaveDriverFirst)) {
                SVProgressHUD.showInfoWithStatus(aty, "请输入车牌号码前缀");
            } else {
                if (StringUtils.isEmpty(mSavePlateNum)) {
                    SVProgressHUD.showInfoWithStatus(aty, "请输入车牌号码");
                } else {
                    if (StringUtils.isEmpty(mSaveTel)) {
                        SVProgressHUD.showInfoWithStatus(aty, "请输入联系电话");
                    } else {
                        if (StringUtils.isEmpty(mSaveIdCard)) {
                            SVProgressHUD.showInfoWithStatus(aty, "请输入身份证号码");
                        } else {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * 选择车牌号前缀
     */
    private void chooseCarNum() {
        Util.alertBottomWheelOption(aty, mSaveCarLs, new Util.OnWheelViewClick() {
            @Override
            public void onClick(View view, int postion) {
                mSaveDriverFirst = mSaveCarLs.get(postion);
                mTxtDriverFirst.setText(mSaveDriverFirst);
            }
        }, 16);
    }

    @OnClick({R.id.id_driver_add_btn, R.id.id_driver_first_txt})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_driver_add_btn:
                //添加司机
                if (checkData()) {
                    ((OilMealPresenter) presenter).addDriverInfo(mSaveName, mSaveDriverFirst + mSavePlateNum, mSaveTel, mSaveIdCard, mSaveOilNum);
                }
                break;
            case R.id.id_driver_first_txt:
                chooseCarNum();
                break;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.ADD_DRIVERS)) {
                //添加司机成功
                SVProgressHUD.showSuccessWithStatus(aty, "添加成功");
                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.ADD_DRIVERS;
                EventBus.getDefault().post(event);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
            }
        }
    }
}
